package com.grq.mis.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.grq.mis.entity.Department;
import com.grq.mis.entity.Role;
import com.grq.mis.entity.User;
import com.grq.mis.entity.UserRole;
import com.grq.mis.exception.BusinessException;
import com.grq.mis.exception.ResultEnum;
import com.grq.mis.model.sys.Me;
import com.grq.mis.service.DepartmentService;
import com.grq.mis.service.RoleService;
import com.grq.mis.service.UserRoleService;
import com.grq.mis.service.UserService;
import com.grq.mis.validate.UserValidate;
import org.beetl.sql.core.page.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private DepartmentService departmentService;

    @SaCheckPermission("user:list")
    @GetMapping("/page")
    public String page(
            Model model,
            @RequestParam(defaultValue = "1") long page,
            @RequestParam(defaultValue = "20") int size,
            String key
    ) {

        // 带入参数
        Map<String, Object> paras = new HashMap<>();
        if (!StringUtils.isEmpty(key)) {
            paras.put("key", "%" + key.trim() + "%");
        }

        PageResult<User> result = userService.page("user.page", paras, page, size);
        model.addAttribute("data", result);

        model.addAttribute("key", key);

        return "user/page.html";
    }

    @SaCheckPermission("user:add")
    @GetMapping("/addForm")
    public String addForm(Model model) {

        List<Role> roles = roleService.all();
        model.addAttribute("roles", roles);

        List<Department> departments = departmentService.createLambdaQuery().andEq(Department::getIsDisable, false).select();
        model.addAttribute("departments", departments);

        return "user/add.html";
    }

    @SaCheckPermission("user:add")
    @PostMapping("/add")
    public String add(Model model, User user, Long[] roleIds) {

        UserValidate.add(user);
        userService.addUser(user, roleIds);

        return frameSuccess(model, ResultEnum.SUCCESS, "添加账号成功");
    }

    @SaCheckPermission("user:update")
    @GetMapping("/updateForm")
    public String updateForm(@RequestParam Long id, Model model) {

        User user = userService.single(id);
        if (user == null) {
            throw new BusinessException(ResultEnum.USER_IS_NULL);
        }

        model.addAttribute("user", user);

        List<Role> roles = roleService.all();
        model.addAttribute("roles", roles);

        List<Department> departments = departmentService.createLambdaQuery().andEq(Department::getIsDisable, false).select();
        model.addAttribute("departments", departments);

        List<Long> roleIds = new ArrayList<>();
        List<UserRole> userRoles = userRoleService.createLambdaQuery().andEq(UserRole::getUserId, user.getId()).select();
        for (UserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
        }
        model.addAttribute("roleIds", roleIds);

        return "user/update.html";
    }

    @SaCheckPermission("user:update")
    @PostMapping("/update")
    public String update(Model model, User user, Long[] roleIds) {

        UserValidate.update(user);

        userService.updateUser(user, roleIds);

        return frameSuccess(model, ResultEnum.SUCCESS, "修改账号成功");
    }

    @SaCheckPermission("user:reset")
    @GetMapping("/reset")
    public String reset(@RequestParam Long id, RedirectAttributes attr) {

        userService.reset(id);

        return pageSuccess(attr, "/user/page", ResultEnum.SUCCESS, "重置密码成功");
    }

    @GetMapping("/passwordForm")
    public String passwordForm(Model model) {
        Me me = me();
        model.addAttribute("me", me);
        return "me/password.html";
    }

    @PostMapping("/password")
    public String password(Model model, @RequestParam String oldPassword, @RequestParam String newPassword) {

        Me me = me();
        userService.password(me, oldPassword, newPassword);

        return frameSuccess(model, ResultEnum.SUCCESS, "修改密码成功");
    }

    @GetMapping("/info")
    public String info(Model model) {
        Me me = me();

        User user = userService.single(me.getId());
        if (user == null){
            throw new BusinessException(ResultEnum.USER_IS_NULL);
        }
        user.setPassword(null);
        model.addAttribute("user",user);

        if (user.getDepartmentId() != null){
            Department department = departmentService.single(user.getDepartmentId());
            model.addAttribute("department",department);
        }

        List<Role> roles = roleService.findByUserId(user.getId());
        model.addAttribute("roles",roles);

        return "me/info.html";
    }

}
